(ns xuan-clj.middleware.wrappers
  (:require [ring.util.http-response :as response]
            [xuan-clj.service.token :as token]))

(defn wrap-ok [data]
  {:resultCode 200 :msg "操作成功" :data data}
  )

(defn wrap-ok-response [data]
  (-> data wrap-ok response/ok)
  )

(defn- make-error-map [msg]
  {:resultCode 500 :msg msg}
  )

(defn wrap-error-response [message]
  (-> message
      make-error-map
      response/ok
      )
  )

(defn wrap-page [total current data]
  {:total total :current current :records data}
  )

(defn wrap-verify-token [handler]
  (fn [request]
    (let [token (-> request :headers (get "token"))]
      (cond
        ;; token校验不通过
        (or (nil? token)
            (not (token/verify-token token)))
        (response/ok {:resultCode 419 :msg "token无效"})

        ;; token过期
        (token/token-expires? token)
        (response/ok {:resultCode 419 :msg "token过期"})

        ;; 正常放行
        :else
        (handler request)))))
